//
//  HYUserAccountViewModel.swift
//  iOSWeibo
//
//  Created by why on 16/7/21.
//  Copyright © 2016年 王浩宇. All rights reserved.
//

import UIKit

/// 负责处理 HMUserAccount的业务逻辑
/// 网络请求
/// 字典转模型
/// 保存模型到沙盒中
/// 沙盒加载模型到内存中

class HYUserAccountViewModel: NSObject {
    
    static let sharedUserAccountViewModel: HYUserAccountViewModel = HYUserAccountViewModel()
    
    var userAccount: HYUserAccount?
    
    var userLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    let userAccountFile = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    
    override init() {
        super.init()
        
        userAccount = loadAccount()
    }
    
    /// 获取用户名称和头像
    func loadUserInfo(completion: (error: NSError?) ->()) {
        //判断没有access_token,不发网络请求
        guard let access_token = userAccount?.access_token else {
            print("没有access_token,不发网络请求")
            return
        }
        //没有uid,不发网络请求
        guard let uid = userAccount?.uid else {
            print("没有uid,不发网络请求")
            return
        }
        
        let urlString = "2/users/show.json"
        
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        
        // 发送请求
        HYNetworkTool.sharedInstance.GET(urlString, parameters: parameters, progress: nil, success: { (_, responseObjce) -> Void in
            // 获取用户名称和头像地址
            let dict = responseObjce as? [String: AnyObject]
            let screen_name = dict?["screen_name"] as? String
            let avatar_large = dict?["avatar_large"] as? String
            
            // 给userAccount赋值
            self.userAccount?.screen_name = screen_name
            self.userAccount?.avatar_large = avatar_large
            
            // 将模型重新保存到沙盒中
            self.saveUserAccount(self.userAccount!)
            
            //告诉调用的人获取到了数据
            completion(error: nil)
            
            }) { (_, error) -> Void in
                print("请求用户数据失败: \(error)")
                //告诉调用的人获取数据失败了
                completion(error: error)
        }
    }
    
    /**
     去服务器请求AccessToken
     
     - parameter code:       code
     */
    func loadAccessToken(code:String, completion: (error: NSError?) -> Void) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 使用AFN发送POST请求
        HYNetworkTool.sharedInstance.POST(urlString, parameters: parameters, progress: nil, success: { (_, resopnseOjbect) -> Void in
            //            print("resopnseOjbect: \(resopnseOjbect)")
            
            let dict = resopnseOjbect as! [String: AnyObject]
            self.userAccount = HYUserAccount(dict: dict)
            
            print("userAccount = \(self.userAccount)")
            
            self.saveUserAccount(self.userAccount!)
            
            completion(error: nil)
            
            }) { (_, error) -> Void in
                print("error: \(error)")
                
                completion(error: error)
        }
    }
    
    ///保存模型到沙盒中
    private func saveUserAccount(userAccount: HYUserAccount) {
        NSKeyedArchiver.archiveRootObject(userAccount,toFile: self.userAccountFile)
    }
    
    ///加载沙盒中的帐号
    private func loadAccount() -> HYUserAccount? {
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(userAccountFile) as? HYUserAccount
        
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending
        {
            print("没有过期的帐号")
            return account
        }
        
        return nil
    }
}


